package com.simp.utils.detail;


import com.simp.expection.GlobalException;
import com.simp.page.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * @author pan.shun
 * @since 2022/3/14 19:55
 */
@Slf4j
public class CommonFileUtilsDetails {


    /**
     * 文件授权
     */
    protected static void changeFilePermission(String fileName) {
        try {
            Runtime run = Runtime.getRuntime();
            Process process = run.exec(String.format("chmod 777 %s", fileName));
            int exeResult = process.waitFor();
            if (exeResult == 0) {
                log.info("自动对文件: {} 授权 777", fileName);
            }
        } catch (Exception var4) {
            log.error("授权失败 ，{}", var4);
        }
    }

    /**
     * 解压
     *
     * @param zipFile 解压文件
     * @param descDir 解压至目录
     */
    protected static void unZip(File zipFile, String descDir) {
        try (ZipArchiveInputStream inputStream = getZipFile(zipFile)) {
            File pathFile = new File(descDir);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            ZipArchiveEntry entry = null;
            while ((entry = inputStream.getNextZipEntry()) != null) {
                if (entry.isDirectory()) {
                    File directory = new File(descDir, entry.getName());
                    directory.mkdirs();
                } else {
                    OutputStream os = null;
                    try {
                        os = new BufferedOutputStream(new FileOutputStream(new File(descDir, entry.getName())));
                        //输出文件路径信息
                        log.info("解压文件的当前路径为:{}", descDir + entry.getName());
                        IOUtils.copy(inputStream, os);
                    } finally {
                        IOUtils.closeQuietly(os);
                    }
                }
            }
            final File[] files = pathFile.listFiles();
            if (files != null && files.length == 1 && files[0].isDirectory()) {
                // 说明只有一个文件夹
                FileUtils.copyDirectory(files[0], pathFile);
                //免得删除错误， 删除的文件必须在/data/demand/目录下。
                boolean isValid = files[0].getPath().contains("/data/www/");
                if (isValid) {
                    FileUtils.forceDelete(files[0]);
                }
            }
            log.info("******************解压完毕********************");

        } catch (Exception e) {
            log.error("[unzip] 解压zip文件出错 ,{}", e);
        }
    }

    /**
     * 将文件内容以字符串格式输出
     */
    protected static String readFileContent(File file) {
        try {
            StringBuilder str = new StringBuilder();
            FileReader fileReader = new FileReader(file);
            char[] chars = new char[5];
            int length;
            while ((length = fileReader.read(chars)) != -1) {
                String s = new String(chars, 0, length);
                str.append(s);
            }
            fileReader.close();
            return str.toString();
        } catch (IOException e) {
            log.error("文件读取失败, {} ", e);
            throw new GlobalException("文件读取失败");
        }
    }

    /**
     * 执行命令
     */
    protected static String execCommand(String cmd) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            InputStream is = proc.getInputStream();
            InputStream es = proc.getErrorStream();
            String line;
            BufferedReader br;
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder str = new StringBuilder();
            while ((line = br.readLine()) != null) {
                str.append(line).append("\r\n");
            }
            br = new BufferedReader(new InputStreamReader(es, "UTF-8"));
            while ((line = br.readLine()) != null) {
                str.append(line).append("\r\n");
            }
            return str.toString();
        } catch (Exception e) {
            return e.toString();
        }
    }

    /**
     * 将文件或目录压缩成zip
     * * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     */
    protected static void fileToZip(String filePath, File targetZipFile, boolean KeepDirStructure) {
        File file = new File(filePath);
        if (file.exists()) {
            try {
                if (targetZipFile.getName().contains("zip")) {
                    FileOutputStream fos1 = new FileOutputStream(targetZipFile);
                    toZip(filePath, fos1, KeepDirStructure);
                } else {
                    throw new GlobalException("压缩文件只能是zip格式");
                }
            } catch (Exception e) {
                log.error("压缩异常 ,{}", e);
            }
        } else {
            throw new GlobalException("路径不存在");
        }
    }

    /**
     * 将多个File压缩成zip
     */
    protected static void filesToZip(List<File> fileList, File targetZipFile) {
        try {
            if (targetZipFile.getName().contains("zip")) {
                FileOutputStream fos2 = new FileOutputStream(targetZipFile);
                toZip(fileList, fos2);
            } else {
                throw new GlobalException("压缩文件只能是zip格式");
            }
        } catch (FileNotFoundException e) {
            log.error("压缩异常 ,{}", e);
        }
    }

    /**
     * 将目录压缩成压缩包
     *
     * @param srcDir           压缩文件夹路径
     * @param out              压缩文件输出流
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    private static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) {
        try {
            long start = System.currentTimeMillis();
            ZipOutputStream zos = null;
            try {
                zos = new ZipOutputStream(out);
                File sourceFile = new File(srcDir);
                compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
                long end = System.currentTimeMillis();
                System.out.println("压缩完成，耗时：" + (end - start) + " ms");
            } catch (Exception e) {
                throw new RuntimeException("zip error from ZipUtils", e);
            } finally {
                if (zos != null) {
                    try {
                        zos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (RuntimeException e) {
            log.error("目录压缩异常 ,{}", e);
            throw new GlobalException("目录压缩异常");
        }
    }

    /**
     * 文件压缩
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    private static void toZip(List<File> srcFiles, OutputStream out) {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            log.error("文件压缩异常 ,{}", e);
            throw new GlobalException("文件压缩异常");
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         <p>
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }

            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }

                }
            }

        }
    }

    private static ZipArchiveInputStream getZipFile(File zipFile) throws Exception {
        return new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
    }

    /**
     * 将文件大小转成对应格式
     */
    protected static String fileSizeTran(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.00");
        if (size >= 1024 * 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        } else if (size >= 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        } else if (size >= 1024) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        } else if (size < 1024) {
            if (size <= 0) {
                bytes.append("0B");
            } else {
                bytes.append((int) size).append("B");
            }
        }
        return bytes.toString();
    }

    /**
     * 获取文件的创建时间
     */
    protected static String getFileCreateTimeDetail(String filePath) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        File file = new File(filePath);
        try {
            Path path = Paths.get(filePath);
            BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            BasicFileAttributes attr = basicview.readAttributes();
            return format.format(new Date(attr.creationTime().toMillis()));
        } catch (Exception e) {
            e.printStackTrace();
            return format.format(new Date(file.lastModified()));
        }
    }

    /**
     * 下载文件 传入HttpServletResponse对象response 和 文件保存位置path
     */
    protected static void downLoadFile(HttpServletResponse response, String path) {
        try {
            response.setCharacterEncoding("UTF-8");
            //response.setContentType("application/force-download");//应用程序强制下载
            File file = new File(path);
            //如果文件不存在
            if (!file.exists()) {
                String msg = "文件不存在!";
                System.out.println(msg);
                PrintWriter out = response.getWriter();
                out.write(msg);
                out.flush();
                out.close();
                return;
            }
            String simpleName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
            String newFileName = new String(simpleName.getBytes(), "utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + newFileName);
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(
                    response.getOutputStream());
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param file     上传文件
     * @param maxSize  文件最大容量，单位MB
     * @param filePath 文件路径
     */
    protected static R uploadFileDetail(MultipartFile file, long maxSize, String filePath) {
        if (file.isEmpty()) {
            throw new GlobalException("文件内容为空");
        }
        long size = file.getSize();
        if (size > maxSize * 1024 * 1024) {
            throw new GlobalException("文件大小超过30MB，上传失败");
        }
        // 获取文件名
        File destFile = new File(filePath + file.getOriginalFilename());
        // 检测是否存在目录
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(destFile);
            return R.success("上传成功");
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return R.error("上传失败");
    }
}
